<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <!-- 使用双向绑定的方式获取查询的参数 -->
          <el-input v-model="filters.keywords" placeholder="输入姓名或电话或邮箱"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="employeeQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
  <!--
     data: 表单中的数据绑定
     v-loading: 忙等框
     selection-change: 用于表中复选框选择的触发的事件，做批量操作
     Employees：页面加载完后发送请求由后台查询出数据响应到前台 []
    -->
    <el-table :data="Employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>

      <el-table-column prop="username" label="姓名" width="120" sortable>
      </el-table-column>

      <el-table-column prop="age" label="年龄" width="80" sortable>
      </el-table-column>

      <el-table-column prop="phone" label="电话" width="120" sortable>
      </el-table-column>

      <el-table-column prop="email" label="邮箱" width="180" sortable>
      </el-table-column>

      <el-table-column prop="department.name" label="部门" width="120" sortable>
      </el-table-column>

      <el-table-column prop="shop.name" label="所在店铺" width="120" sortable>
      </el-table-column>

<!--      <el-table-column prop="password" label="密码" width="300" sortable>
      </el-table-column>-->

<!--      <el-table-column prop="salt" label="盐值" width="300" sortable>
      </el-table-column>-->





      <!--<el-table-column prop="state" label="是否启用" width="100" :formatter="formatSex" sortable>
      </el-table-column>-->
      <el-table-column label="状态" width="100">
        <template scope="scope">
          <span style="color: #00fc00" v-if="scope.row.state == 1">在职</span>
          <span style="color: red" v-else-if="scope.row.state == 0">离职</span>
          <span style="color: gray" v-else>未知</span>
        </template>
      </el-table-column>



      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>


    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--   disabled: 使按钮失效   -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
           @current-change="handleCurrentChange"
           :page-size="pageSize"
           :total="totals"
           style="float:right;">

      </el-pagination>
    </el-col>

    <!--编辑界面
      rules: 表单验证，用于判断用户是否输入数据
      ref： 点击提交按钮时，再次验证是否输入数据 - 为当前模态框取名

    -->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">

      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">

        <el-form-item label="姓名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="editForm.age" auto-complete="off"></el-input>
        </el-form-item>

<!--        <el-form-item label="盐值" prop="salt">
          <el-input v-model="editForm.salt" auto-complete="off"></el-input>
        </el-form-item>-->

        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="校验密码" prop="confirmPassword">
          <el-input v-model="editForm.confirmPassword" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门" prop="department_id">
          <!--

          el-select  下拉框
		      v-model="editForm.manager_id" - 回显数据
		      value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
		      回显机制：

		      v-model="editForm.manager_id" 与 :value="item.id"对应(v-for中的变量的item中的id)对应
		      如果item中的id与manager_id相同则显示label绑定的item.username
		      注意：v-model=""中的值要与 :value=""中的值类型对应

		      具体例子可以参见官网
          //验证回显的数据绑定
          -->
          <el-select v-model="editForm.department_id" placeholder="请选择" clearable>

            <!--
                v-for: 循环
                key：一个键值，唯一即可

                label：选择后或初始时匹配到的要显示的数据
                value：向后台发送的数据
            -->
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item.id">

              <!--下拉单中显示的内容-->
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>

        </el-form-item>


        <el-form-item label="店铺" prop="shop_id">
          <el-select v-model="editForm.shop_id" placeholder="请选择" clearable>

            <!--
                v-for: 循环
                key：一个键值，唯一即可

                label：选择后或初始时匹配到的要显示的数据
                value：向后台发送的数据
            -->
            <el-option
                v-for="item in shops"
                :key="item.id"
                :label="item.name"
                :value="item.id">

              <!--下拉单中显示的内容-->
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="角色" prop="role_id">
          <el-select v-model="editForm.role_id" placeholder="请选择" clearable>
            <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id">

              <!--下拉单中显示的内容-->
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">在职</el-radio>
            <el-radio class="radio" :label="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>






      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <!--<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addForm.sex">
            <el-radio class="radio" :label="1">男</el-radio>
            <el-radio class="radio" :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
        </el-form-item>
        <el-form-item label="地址">
          <el-input type="textarea" v-model="addForm.addr"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>-->`
  </section>
</template>

<script>

export default {
  data() {
    return {
      roles: [],
      shops: [],
      departments: [],
      title: "",
      filters: {
        keywords: ''
      },
      Employees: [],
      totals: 0,
      currentPage: 1,
      pageSize: 5,
      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        /**
         *  id: null,
          username: '',
          phone: '',
          email: '',
          salt: '',
         password: '',
         age: null,
         state: 1,
         department_id: null,
         logininfo_id: null,
         shop_id: null
         */

        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        /*salt: [
          { required: true, message: '请输入盐值', trigger: 'blur' }
        ],*/
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        /*department_id: [
          { required: true, message: '请输入部门', trigger: 'change' }
        ],
        shop_id: [
          { required: true, message: '请输入店铺', trigger: 'change' }
        ],
        state: [
          { required: true, message: '请输入状态', trigger: 'change' }
        ],*/

      },
      //编辑界面数据
      editForm: {
        id: null,
        username: '',
        phone: '',
        email: '',
        //salt: '',
        password: '',
        confirmPassword: '',
        age: null,
        state: 1,
        department_id: null,
        logininfo_id: null,
        shop_id: null,
        role_id: null,
      },

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //新增界面数据
      /*addForm: {
        name: '',
        sex: -1,
        age: 0,
        birth: '',
        addr: ''
      }*/

    }
  },
  methods: {
    //性别显示转换
    /*formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },*/
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmployees();
    },


    //获取编辑模态框中店铺的回显数据
    getShops() {
      this.$http.get("/shop").then(res=>this.shops = res.data);
    },

    //获取编辑模态框中员工部门的回显数据
    getDepartments() {
       this.$http.get("/department").then(res=>this.departments = res.data);
    },

    //模态框中角色的回显查询
    getRoles(){
      this.$http.get("/role")
          .then(res=>{
            this.roles = res.data;
          });

    },

    /**
     * 问题：当在非第一页查询时，如果条件查询的结果没有超过一页数据，则会显示空屏，
     * 解决：条件查询配合分页查询，显示第一页的数据
     */
    employeeQuery(){
      this.currentPage  = 1;
      this.getEmployees();
    },

    //获取用户列表
    getEmployees() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keywords: this.filters.keywords
      };
      this.listLoading = true;


      //发送异步请求获取数据
      this.$http.put("/employee", para)
          .then(res => {
            //alert("success")
            //关闭忙等框
            this.listLoading = false;
            this.totals = res.data.totals;
            this.Employees = res.data.data;
          }).catch(res => alert("fail!"));
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        //提示框
        type: 'warning'
      }).then(() => {
        //当点击确认时执行

        //忙等框
        this.listLoading = true;

        //获取数据发送请求
        this.$http.delete("/employee/" + row.id)
            .then(res => {
                //关闭忙等框
                this.listLoading = false;
                if(res.data.success){
                  //成功删除
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                }else{
                  //删除失败
                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }

              //操作完成后，刷新页面
              //当删除完当前页面的最后一条数据后，可以就显示空页面
              //或者每次删除完就重新显示第一页数据
              // this.currentPage = 1;
              this.getEmployees();

            }).catch(res => {
              //发生异常或错误时执行
              this.$message({
                message: '系统异常，稍后重试',
                type: 'error'
          });

        });

        //NProgress.start();
        /*let para = { id: row.id };
        removeEmployee(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getEmployees();
        });*/
      }).catch(() => {
        //点击取消时执行
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";

      //获取模态框中店铺的回显的数据
      this.getShops();

      //获取模态框中部门回显的数据
      this.getDepartments();

      //获取角色的回显数据
      this.getRoles();

      this.editFormVisible = true;

      //通过克隆方式获取回显数据
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      //修改标题
      this.title = "增加";

      //获取模态框中店铺的回显的数据
      this.getShops();

      //获取模态框中部门回显的数据
      this.getDepartments();

      //获取角色的回显数据
      this.getRoles();

      //清空模态框
      this.editForm = {
        id: null,
        username: '',
        phone: '',
        email: '',
        //salt: '',
        password: '',
        confirmPassword: '',
        age: null,
        state: 1,
        department_id: null,
        logininfo_id: null,
        shop_id: null,
        role_id: null,
      },

      this.editFormVisible = true;

    },
    //编辑页面的提交按钮的事件绑定函数
    editSubmit: function () {

      //this.$refs.editForm 表单的验证
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();

            //通过克隆，获取一份数据，因为使用的是双向绑定
            let para = Object.assign({}, this.editForm);

            //发送请求
            this.$http.post("/employee", para)
              .then(res => {
                //关闭忙等框
                this.editLoading = false;


                if(res.data.success) {
                  //操作成功

                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });


                }else {
                  //操作失败

                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }

                //关闭模态框
                this.editFormVisible = false;

                //刷新页面
                this.getEmployees();

              }).catch(res => {
                //发生异常

                //关闭忙等框
                this.editLoading = false;
                this.$message({
                  message: '网络延时，请稍后重试',
                  type: 'error'
                });


                //关闭模态框
                this.editFormVisible = false;

                //刷新页面
                this.getEmployees();
            })

          });
        }
      });
    },


    selsChange: function (sels) {
      //复选框选择时将选择的数据记录到data数据模型中的sels中
      this.sels = sels;
      console.log(sels);
    },


    //批量删除
    batchRemove: function () {

      //map 数组的方法映射
      var ids = this.sels.map(item => item.id);


      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        /*let para = { ids: ids };
        batchRemoveEmployee(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getEmployees();
        });*/

        //发送请求
        this.$http.patch("/employee", ids).then((res) => {
          this.listLoading = false;

          if(res.data.success) {
            //success
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }

          //操作成功后刷新页面，可以继续查询当前页的内容,即使当前页的数据被删除完
          this.getEmployees();

        }).catch(res =>{
          //当产生异常时
          this.listLoading = false;
          this.$message({
            message: '网络延迟，请稍后重试！',
            type: 'error'
          });
        });
      }).catch(() => {
        //点击取消按钮
      });
    }
  },
  mounted() {
    this.getEmployees();
  }
}

</script>

<style scoped>

</style>
